package com.yungu.swift.api.utils;

import com.yungu.swift.utils.Base64Utils;
import com.yungu.swift.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 三方互通的AES对称性加密
 */

class AESCipher {

    private static final String IV_STRING = "16-Bytes--String";

    static String encryptAES(String content, String key) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_STRING.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] encryptedBytes = cipher.doFinal(content.getBytes("UTF-8"));
            return Base64Utils.encode(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    static String decryptAES(String content, String key) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_STRING.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

            byte[] decryptedBytes = cipher.doFinal(Base64Utils.decode(content));
            return new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
